﻿

$(function () {
    Show()
})
//显示工单信息
function Show() {
    layui.use(function () {
        var table = layui.table;
        // 点击导出按钮
        document.getElementById('exportBtn').addEventListener('click', function () {
            var checkStatus = table.checkStatus('WorkOrdertable');  // 获取当前表格的选中状态
            var selectedData = checkStatus.data;  // 获取选中的数据
            if (selectedData.length === 0) {
                alert('请先选择要导出的数据!');
                return;
            }
            var filteredData = selectedData.map(function (item) {
                // 创建一个新对象，只包含您想要的属性
                return {
                    '工单编号': item.WorkOrderCode,
                    '工单状态': item.WorkOrderSart,
                    '优先级': item.Priority,
                    '计划开始日期': item.StartDate,
                    '计划结束日期': item.EndDate,
                    '成品编号': item.FinishedProductCode,
                    '计划产量': item.Production,
                    '车间': item.WorkShop,
                    '工艺路线': item.ProcessRoute,
                    '当前工序': item.CurrenProcess,
                    '生产编号': item.ProductionNumber,
                    '订单编号': item.OrderCode,
                    '创建人': item.CreatedBy,
                    '创建时间': item.CreatedDate,
                };
            });

            // 使用 XLSX 导出选中的数据
            var wb = XLSX.utils.book_new();
            var ws = XLSX.utils.json_to_sheet(filteredData); // 将选中的数据转换为工作表
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

            // 导出为 Excel 文件
            XLSX.writeFile(wb, '工单列表.xlsx');
        });

        var WorkOrdersCode = $("#WorkOrdersCode").val();
        var WorkOrdersState = $("#WorkOrdersState").val();
        var AddDate = $("#AddDate").val();

        // 先进行表格的初始渲染
        table.render({
            elem: '#WorkOrdertable',  // 表格元素的选择器
            page: {
                limit: 5,
                limits: [5, 8, 10]
            },
            cols: [[
                { type: 'checkbox', fixed: 'left' },
                { field: 'WorkOrderCode', title: '工单编号' },
                { field: 'WorkOrderSart', title: '工单状态' },
                { field: 'Priority', title: '优先级' },
                { field: 'StartDate', title: '计划开始日期' },
                { field: 'EndDate', title: '计划结束日期' },
                { field: 'FinishedProductCode', title: '成品编号' },
                { field: 'Production', title: '计划产量' },
                { field: 'WorkShop', title: '车间' },
                { field: 'ProcessRoute', title: '工艺路线' },
                { field: 'CurrenProcess', title: '当前工序' },
                { field: 'ProductionNumber', title: '生产编号' },
                { field: 'OrderCode', title: '订单编号' },
                { field: 'CreatedBy', title: '创建人' },
                { field: 'CreatedDate', title: '创建时间' },
                
                {
                    field: '', title: '操作', templet: function (d) {
                        return '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="XiafaData(' + d.WorkOrderId + ')"><i class="layui-icon layui-icon-edit"></i>工单下发</a> ' +
                            '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="showData(' + d.WorkOrderId + ')"><i class="layui-icon layui-icon-edit"></i>详情</a> ' +
                            '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="editData(\'' + d.WorkOrderId + '\', \'' + '已暂停' + '\')"><i class="layui-icon layui-icon-edit"></i>暂停</a> ' +
                            '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="editData(\'' + d.WorkOrderId + '\', \'' + '已关闭' + '\', \'' + d.WorkOrderSart + '\')"><i class="layui-icon layui-icon-delete"></i>关单</a>';
                    }

                }
            ]],
            // 初始时可以先不加载数据，等待 ajax 请求成功后再更新
            data: []
        });

        // 创建表格实例
        $.ajax({
            url: "../Manufacture/WorkOrderList",
            type: "get",
            data: {
                PageIndex: 1,
                PageSize: 100,
                token: localStorage.getItem("token"),
                WorkOrderCode: WorkOrdersCode,
                WorkOrderSart: WorkOrdersState,
                CreatedDate: AddDate
            },

            success: function (data) {
                data = JSON.parse(data);
                console.log(data.Data.list);
                // 在 ajax 请求成功后，使用正确的表格 ID 进行 reload
                table.reload('WorkOrdertable', {
                    page: {
                        limit: 5,
                        limits: [5, 8, 10]
                    },
                    data: data.Data.list
                });
            },
            error: function () {
                console.log("请求失败");
            }
        });

    });

}
//跳转详情
window.showData = function showData(WorkOrderId) {
    localStorage['WorkOrderId'] = WorkOrderId;

    location.href = '/Manufacture/GetByShowWorkOrder';
}
// 暂停/关闭工单
window.editData = function (WorkOrderId, WorkOrderSartat, WorkOrderSart) {
    if (WorkOrderSartat == "已暂停") {
        layer.confirm('确定要暂停该工单吗？', function () {
            $.ajax({
                type: "post",
                url: "../Manufacture/Guandan",  // 替换为实际的后台删除数据接口地址
                data: {
                    WorkOrderId: WorkOrderId,
                    WorkOrderSart: WorkOrderSartat,
                    token: localStorage.getItem("token")
                },
                success: function (res) {
                    console.log(res)
                    var res = JSON.parse(res)
                    if (res.Code == 1) {
                        layer.alert("暂停成功");
                        Show();  // 重新加载数据，刷新表格显示

                    } else {
                        layer.alert("暂停失败");


                    }

                },
                error: function () {
                    layer.msg('暂停失败，请稍后重试', {
                        time: 2000,
                        icon: 2

                    });

                }
            });


        });
    }
    if (WorkOrderSartat == "已关闭") {
        if (WorkOrderSart == "生产中") {
            layer.confirm('当前工单正在生产中,确定要关闭吗？', function () {
                $.ajax({
                    type: "post",
                    url: "../Manufacture/Guandan",  // 替换为实际的后台删除数据接口地址
                    data: {
                        WorkOrderId: WorkOrderId,
                        WorkOrderSart: WorkOrderSartat,
                        token: localStorage.getItem("token")
                    },
                    success: function (res) {
                        console.log(res)
                        var res = JSON.parse(res)
                        if (res.Code == 1) {
                            layer.alert("关闭成功");
                            Show();  // 重新加载数据，刷新表格显示

                        } else {
                            layer.alert("关闭失败");


                        }

                    },
                    error: function () {
                        layer.msg('关闭失败，请稍后重试', {
                            time: 2000,
                            icon: 2

                        });

                    }
                });


            });
        }
        else {
            layer.confirm('确定要关闭该工单吗？', function () {
                $.ajax({
                    type: "post",
                    url: "../Manufacture/Guandan",  // 替换为实际的后台删除数据接口地址
                    data: {
                        WorkOrderId: WorkOrderId,
                        WorkOrderSart: WorkOrderSartat,
                        token: localStorage.getItem("token")
                    },
                    success: function (res) {
                        console.log(res)
                        var res = JSON.parse(res)
                        if (res.Code == 1) {
                            layer.alert("关闭成功");
                            Show();  // 重新加载数据，刷新表格显示

                        } else {
                            layer.alert("关闭失败");


                        }

                    },
                    error: function () {
                        layer.msg('关闭失败，请稍后重试', {
                            time: 2000,
                            icon: 2

                        });

                    }
                });


            });
        }
        
    }
};
//弹窗
window.XiafaData = function XiafaData(WorkOrderId) {

    layer.open({
        type: 1, //page 层类型
        area: ['800px', '400px'],
        title: '工单下发',
        shade: 0.6, //遮罩透明度
        shadeClose: true, //点击遮罩区域，关闭弹层
        maxmin: true, //允许全屏最小化
        anim: 0, //0-6 的动画形式，- 1 不开启
        content: `
    <div class="form-container">
        <form class="layui-form" action="">
            <div class="layui-form-item">
               
                <div class="layui-inline">
                    <label class="layui-form-label">工单编号：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="WorkOrderCode1" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
               
            
            
            <div class="layui-form-item">
            <div class="layui-inline">
                    <label class="layui-form-label">成品编号：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="FinishedProductCode1" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">成品名称：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="FinishedProduct1" name="ProcessPouteNumber" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
                
               

            </div>
           
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">工艺路线：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="ProcessRoute1" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">计划产量：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="Number1" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
               
            </div>
            <div class="layui-form-item">
             <div class="layui-inline">
                    <label class="layui-form-label">单次产量：</label>
                    <div class="layui-input-inline">
                        <input type="text" id="SingleNumber1" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>

            </div>
             <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" id="XiafaWorkOrder" class="layui-btn" lay-submit lay-filter="formSubmit">确认下发</button>
                    <button type="reset" class="layui-btn layui-btn-primary" onclick="location.href='/Manufacture/ShowWorkOrder'">取消</button>
                </div>
            </div>
        </form>
      

    </div>`,
        success: function () {
            //form.render()
            XiaFaOrder(WorkOrderId)
            //// 使用事件委托绑定点击事件
            //$(document).on('click', '#DeviceAdd', function () {
            //    DeviceAdd();
            //});
        }
    });


}

//弹窗反填工单信息
window.XiaFaOrder = function XiaFaOrder(WorkOrderId) {
    layui.use(function () {
        var table = layui.table;
        $.ajax({
            type: "get",
            url: "/Manufacture/FabPurch",
            data: {
                WorkOrderId: WorkOrderId,
                token: localStorage.getItem("token")
            },
            success: function (res) {
                var ter = JSON.parse(res)
                console.log(ter.Data)

                $(ter.Data).each(function () {
                    $('#WorkOrderCode1').val(this.WorkOrderCode);
                   
                    $('#FinishedProduct1').val(this.FinishedProduct);
                    $('#FinishedProductCode1').val(this.FinishedProductCode);
                  
                    $('#Number1').val(this.Production);
                    
                    $('#ProcessRoute1').val(this.ProcessRoute);
                    localStorage.setItem("Wid", this.WorkOrderId)
                })

            },

        });
    });
}
var obj2 = {
    WorkOrderId: "",
    WorkOrderSart: "",
    SingleNumber:""
}

layui.use(['table', 'dropdown', 'layer', 'form'], function () {
    var table = layui.table;
    var dropdown = layui.dropdown;
    var layer = layui.layer;
    var form = layui.form;
    var laypage = layui.laypage;
    //修改工单信息
    form.on('submit(formSubmit)', function (data) {
        var field = data.field;
        var checkStatus = table.checkStatus('XiafaWorkOrder');
        field.allocationProdutesList = checkStatus.data.map(function (item) {
            return item;
        });
        console.log(field);//field.products


        obj2.WorkOrderId = localStorage.getItem("Wid")

        obj2.WorkOrderSart = "待生产"
        obj2.SingleNumber = $("#SingleNumber1").val()

        console.log(obj2)
        // 显示填写结果，仅作演示用
        $.ajax({
            url: '../Manufacture/XiaFa',
            type: 'post',
            data: {
                field: obj2,
                token: localStorage.getItem("token")
            },
            success: function (res) {
                var res = JSON.parse(res)
                console.log(field);
                console.log(res);
                if (res.Code > 0) {
                    layer.alert("工单下发成功");
                    location.href = '/Manufacture/ShowWorkOrder'
                } else {
                    layer.alert("工单下发失败");
                }
            }
        });

        return false; // 阻止默认 form 跳转
    });
})